import forge from 'node-forge';

// 公钥内容
const publicKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA+bGTT/LhxL35xrSRajoS
l5UObo81HQE2zEaQgalswwDWw+YahoitPKpt5RYuvYdGsX1Jo6iQG2ck9BnrLno8
WUg7KzryZRz+3MzcXyL7ntiz8fhw3EiEMRoHYqQiaGIGmcu3mJsSnDlBdkStnmNT
xsNfuchmooVGZ8S2abxI5UfnGWW0X6J77qIY5g7bgyEpa8/TWklWw3mghKXTFSCe
r6Y2mhvtnt2A7aRtbubeA+CL93uuBXaoR+efiJ2KeSGIMocSfPIAoWYqW4MmOmzw
FpTJ6QQnAfOewnFvPIvZZiyM/b9QiCGvbfYua23puB+8fb+iQT2KCBu/pyfgtrPA
iQIDAQAB
-----END PUBLIC KEY-----
`;

/**
 * 使用OAEP填充模式加密字符串
 * @param str 要加密的字符串
 * @returns 加密后的base64字符串
 */
export const encrypted = (str: string) => {
    try {
        // 使用crypto-js进行加密，确保与后端的OAEP填充模式匹配
        // const wordArray = CryptoJS.enc.Utf8.parse(str);
        // const base64 = CryptoJS.enc.Base64.stringify(wordArray);
        
        // 需要安装node-forge库
        // npm install node-forge --save
        // npm install @types/node-forge --save-dev
        const publicKeyForge = forge.pki.publicKeyFromPem(publicKey);
        const encrypted = publicKeyForge.encrypt(str, 'RSA-OAEP', {
            md: forge.md.sha1.create(),
            mgf1: {
                md: forge.md.sha1.create()
            }
        });
        
        // 转换为base64格式
        const base64Result = forge.util.encode64(encrypted);
        return base64Result;
    } catch (e) {
        console.error('加密失败:', e);
        return '';
    }
};